package com.gitee.andy.rpc.client;

import java.util.concurrent.ConcurrentHashMap;

import com.gitee.andy.rpc.entity.RpcRequest;
import com.gitee.andy.rpc.entity.RpcResponse;
import com.gitee.andy.rpc.entity.RpcResult;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class RpcClientHandler extends SimpleChannelInboundHandler<RpcResponse> {

	private static ConcurrentHashMap<Long, RpcResult> results = new ConcurrentHashMap<>();

	private Channel channel;

	public RpcResult write(RpcRequest rpcRequest) {
		RpcResult value = new RpcResult(rpcRequest.getSeq());
		results.put(rpcRequest.getSeq(), value);
		channel.writeAndFlush(rpcRequest);
		return value;
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		this.channel = ctx.channel();
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, RpcResponse msg) throws Exception {
		results.remove(msg.getSeq()).setResult(msg);
	}

}
